import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    FlatList,
    TouchableOpacity,
    AsyncStorage,
    Platform,
    StatusBar,
    TextInput,
    KeyboardAvoidingView
} from 'react-native';
import uuid from 'uuid';
import Config from '../../common/Config'
import Utils from '../../common/Utils'
import mqtt from '../../common/mqtt'
import {Toast,ModalIndicator} from 'teaset';
const STORAGE_KEY_TOKEN = '@AsyncStorageDemo:key_token';
const {height, width} = Dimensions.get('window');
export default class ChatMessagesPage extends Component {
    componentDidMount() {
        this._loadInitialState().done();
    }
    async _loadInitialState(){
        try{
            let value=await AsyncStorage.getItem(STORAGE_KEY_TOKEN);
            if(value!==null){
                this._appendMessage(value);
            }else{
                this._appendMessage('');
            }
        }catch(error){
            this._appendMessage('AsyncStorage错误'+error.message);
        }
    }
    _appendMessage=(message)=>{
        this.setState({
            token:this.state.token.concat(message)
        },()=>this.getInfo());
    };
    getInfo=()=>{
        let params={
            "token":this.state.token,
            "toClientId":this.props.toClientId
        };
        this._connect();
        fetch(Config.baseApi+'/IM/selectByTopic',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                if(responseJson.status===0) {
                    alert(JSON.stringify(responseJson));
                    this.setState({
                        data:responseJson.data
                    })
                }else {
                    Toast.message(JSON.stringify(responseJson))
                }
            })
            .catch((error) => {
               Toast.message(JSON.stringify(error))
            });
    };
    constructor(props) {
        super(props);
        this.state = {
            token:'',
            data: [],
            message:''
        };
        this.chatContactId = this.props.toClientId;
        this.chatUsername = this.props.nickname;
        this.chatWithAvatar = this.props.avatar;
    };

    _keyExtractor = (item, index) => index;
    _connect() {
        // TODO: 后期需要写到其他地方
        let id = this.props.toClientId
        const clientId = this.props.toClientId
        console.log(clientId);
        const params = {
            clientId,
            clean: true,
            username: 'mosquitto',
            password: '123',
            reconnectPeriod: 3000, // 重连
        };
        this.client = mqtt.connect('ws://106.14.209.177:9000', params);
        this.client.on('connect', () => {
            const topic = {};
            topic[`$CHAT/${clientId}`] = 1;
            this.client.subscribe(topic);
        });
        this.client.on('reconnect', (res) => {
            const topic = {};
            topic[`$CHAT/${clientId}`] = 1;
            this.client.subscribe(topic);
        });
        // 接收消息
        this.client.on('message', (topic, message) => {
            const msgStr = message.toString();
            const { data } = this.state;
            const msg = JSON.parse(msgStr)
            data.push(msg);
            this.setState({ data })

        });
        // 连接失败
        this.client.on('error', (error) => {
            console.log(error)
        });
    }
    sendMesssage = () => {
        const clientId = this.props.toClientId
        const json = {
            id: uuid(), // 后端去实现唯一的 id
            clientId,
            head: "2bb23fb0-4b69-41d3-ab43-6395d161d15f.png",
            message: this.state.message,
        };
        this.client.publish(`$CHAT/${clientId}`, JSON.stringify(json), {
            qos: 1,
            retain: false
        });
    }
    uploadMessage=()=>{
        let params={
            "token":this.state.token,
            "toClientId":this.props.toClientId,
            "message":this.state.message
        };
        fetch(Config.baseApi+'/IM/publish',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                if(responseJson.status===0) {
                    this.setState({
                        message:''
                    },()=>{
                        this.getInfo()
                    })
                }else {
                    Toast.message(JSON.stringify(responseJson))
                }
            })
            .catch((error) => {
                Toast.message(JSON.stringify(error))
            });
    };

    render() {
        return (
            <View style={styles.container}>
                <StatusBar
                    backgroundColor="black"
                    barStyle="light-content"
                />
                <View style={styles.titleView}>
                    <TouchableOpacity
                        onPress={()=>Actions.NewsTabPage( )}
                        style={styles.goBackView}>
                        <Image
                            source={ImageUtil.WhiteGoBack}
                            style={styles.goBackImg}/>
                        <Text style={{marginLeft:5,fontSize:20,color:'#ffffff'}}>消息</Text>
                    </TouchableOpacity>
                    <Text style={styles.titleMsg}>{this.chatUsername}</Text>
                    <TouchableOpacity
                        onPress={()=>Actions.DetailsPage({id:this.chatContactId})}
                        style={styles.completeView}>
                        <Image source={ImageUtil.Set}/>
                    </TouchableOpacity>
                </View>
                <KeyboardAvoidingView
                    keyboardVerticalOffset={Platform.OS==='ios'?0:26}
                    style={{flex:1,position: 'absolute',zIndex:-1,marginTop:Platform.OS==='ios'?64:44}}
                    behavior={'position'}>
                    <FlatList
                        style={{height:Platform.OS==='ios'?height-109:height-119,width:width}}
                        data={this.state.data}
                        ItemSeparatorComponent={this.middleView}
                        renderItem={this._renderItem}
                        keyExtractor={this._keyExtractor}
                    />
                    <View style={{flexDirection:'row',justifyContent:'center'}}>
                        <TextInput
                            ref={ (ref)=>this.TextInput = ref }
                            autoCapitalize={"none"}
                            underlineColorAndroid={'transparent'}
                            autoCorrect={false}
                            enablesReturnKeyAutomatically
                            multiline
                            numberOfLines={4}
                            maxLength={800}
                            spellCheck={false}
                            defaultValue={this.state.message}
                            returnKeyLabel="换行"
                            style={styles.textInputView}
                            onChangeText={(text)=>{
                                this.setState({
                                    message:text,
                                })
                            }}/>
                        <TouchableOpacity
                            onPress={()=>this.sendMesssage()}
                            style={styles.ButView}>
                            <Text style={{fontSize:15,color:'#ffffff',textAlign:'center'}}>发送</Text>
                        </TouchableOpacity>
                    </View>
                </KeyboardAvoidingView>
                <View style={{height:3,width:width}}/>
            </View>
        );
    }


    middleView=()=>{
      return (
          <View style={{height:15,width:width}}/>
      )
    };

    _renderItem=(item)=>{
        if(item.item.clientId==this.chatContactId){
            return(
                <View>
                    <View style={styles.labelView}>
                        <Image
                            source={{uri:"http://106.14.209.177/upload/"+item.item.head}}
                            style={styles.headImg}/>
                        <View style={styles.labelMsgView}>
                            <Text style={[styles.labelMsg,{color:'#ffffff'}]}>{item.item.message}</Text>
                        </View>
                    </View>
                </View>
            )
        }else {
            return(
                <View style={styles.labelViewChange}>
                    <View style={styles.labelMsgViewChange}>
                        <Text style={styles.labelMsg}>{item.item.message}</Text>
                    </View>
                    <Image
                        source={{uri:"http://192.168.3.14:8080/upload/"+item.item.head}}
                        style={styles.headImgChange}/>
                </View>
            )
        }
    };
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor:'#f6f6f6'
    },
    titleView:{
        backgroundColor:'#000000',
        width:width,
        height:Platform.OS==='ios'?64:44,
        flexDirection:'row',
        justifyContent:'center',
        alignItems:'center'
    },
    goBackView:{
        position: 'absolute',
        top:Platform.OS==='ios'?30:10,left:15,
        flexDirection:'row',
        justifyContent:'center',
        alignItems:'center'
    },
    goBackImg:{
        height:20,
        width:20
    },
    titleMsg:{
        fontSize:17,
        color:'#ffffff',
        marginTop:Platform.OS==='ios'?34:14,
        marginBottom:29/2
    },
    completeView:{
        position: 'absolute',
        right:15,top:Platform.OS==='ios'?30:10
    },
    labelView:{
        flexDirection:'row',
    },
    headImg: {
        marginLeft: 15,
        height: 44,
        width: 44,
        borderRadius: 5,
    },
    labelMsgView:{
        backgroundColor:'#3090dd',
        borderBottomRightRadius:15,
        borderTopRightRadius:15,
        borderBottomLeftRadius:15,
        marginLeft:10
    },
    labelMsg:{
        fontSize:14,
        marginTop:15,
        marginBottom:15,
        marginLeft:13,
        marginRight:13,
        color:'#000000'
    },
    labelViewChange:{
        flexDirection:'row',
        justifyContent:'flex-end'
    },
    headImgChange:{
        marginRight:15,
        width:44,
        height:44,
        borderRadius:5
    },
    labelMsgViewChange:{
        marginRight:10,
        borderBottomRightRadius:15,
        borderBottomLeftRadius:15,
        borderTopLeftRadius:15,
        backgroundColor:'#3090dd',
    },
    textInputView:{
        height:40,
        backgroundColor:'#ffffff',
        color:'#000000',
        fontSize:20,
        borderRadius:5,
        marginLeft:5,
        width:width-75,
        paddingTop:5,
        paddingBottom:5,
        paddingLeft:5,
    },
    ButView:{
        marginLeft:5,
        height:40,
        width:60,
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:'#3090dd',
        borderRadius:5,
    }
});
